package ogmios.components;

import java.net.*;
import java.io.*;
import java.util.*;
import ogmios.core.OgmiosUtilities;
import javax.swing.*;
/**
 * A classloader that will load a new version of a class, regarldess of whether
 * another classloader has cached an older version.
 */
public class NoCacheClassLoader extends ClassLoader
{
 private final Set<String> blacklist;
 public NoCacheClassLoader(ClassLoader template, Set<String> blacklist)
 {
  super(template);
  this.blacklist = blacklist;
 }
 private static String packageName(String name)
 {
  int index = name.indexOf(".");
  return index == -1 ? "" : name.substring(0, index);
 }
 public Class loadClass(String name) throws ClassNotFoundException
 {

  if (blacklist.contains(packageName(name)))
  {
   Class cachedClass = findLoadedClass(name);

   if (cachedClass != null)
     return cachedClass;
   try
   {
    URL url = getResource(name.replace('.','/') + ".class");
    URLConnection connection = url.openConnection();
    InputStream input = connection.getInputStream();
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    for (int data = input.read(); data!=-1; data=input.read())
    {
     buffer.write(data);
    }
    input.close();
    byte[] classBytes = buffer.toByteArray();
    return defineClass(name, classBytes, 0, classBytes.length);
   }
    catch(MalformedURLException ex)
    {
      OgmiosUtilities.showErrorBox(null, ex, "Class:Load Error");
    }
    catch(IOException ex)
    {
      OgmiosUtilities.showErrorBox(null, ex, "Class:Load Error");
    }
    return null;
  }
  else
  {
    return super.loadClass(name);
  }
 }
}